package com.mgfireworks.mgplatform.mgadmin.sys;

import cn.hn.java.summer.exception.BusinessException;
import cn.hn.java.summer.utils.DateUtils;
import cn.hn.java.summer.web.WebApp;
import com.mgfireworks.mgplatform.mgadmin.constants.Constant;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Service
public class FileService {
	
	/**
	 * 店铺发布目录
	 */
	@Value("${shop.work.dir}")
	private String shopWorkDir;

	/**
	 * 上传产品图片
	 * @return 图片路径
	 * @throws BusinessException 
	 */
	public String uploadProductImg(MultipartFile file, int imgType) throws BusinessException{
		//存储路径:/static/images/p/m/yyyyMMdd/hhmmssxxx.jpg
		//保存上传图片
		String imgPath= uploadFile(file,
				imgType==Constant.PRODUCT_MAIN_IMG?Constant.PRODUCT_MAIN_IMG_DIR:Constant.PRODUCT_DETAIL_IMG_DIR,
				".jpg");
		//同步到店铺目录
		synFileToShop(imgPath);
		return imgPath;
	}

	/**
	 * 上传产品类别图片
	 * @return 图片路径
	 * @throws BusinessException
	 */
	public String uploadProductCateImg(MultipartFile file) throws BusinessException{
		//存储路径:/static/images/p/c/yyyyMMdd/hhmmssxxx.jpg
		//保存上传图片
		String imgPath= uploadFile(file,Constant.PRODUCT_CATE_IMG_DIR,".jpg");
		//同步到店铺目录
		synFileToShop(imgPath);
		return imgPath;
	}
	
	/**
	 * 上传文件
	 * @param file
	 * @param saveFile 保存目录
	 * @param ext 后缀
	 * @return 文件路径
	 * @throws BusinessException 
	 * @throws IOException 
	 */
	private String uploadFile(MultipartFile file, String saveFile, String ext) throws BusinessException{
		saveFile+=DateUtils.now(DateUtils.YMD2);
		// /static/images/p/myyyyMMdd/xxx.jpg
		saveFile+=File.separator+DateUtils.now("HHmmss")+""+RandomUtils.nextInt(100, 999)+ext;
		File dest=new File(WebApp.webRootDir+saveFile);
		dest.getParentFile().mkdirs();
		try {
			file.transferTo(dest);
		} catch (IllegalStateException | IOException e) {
			throw new BusinessException("上传文件失败！", e);
		}
		return saveFile;
	}
	
	/**
	 * 同步文件到店铺对应目录
	 * @param file
	 * @return
	 * @throws BusinessException 
	 */
	private void synFileToShop(String file) throws BusinessException{
		String srcFile=WebApp.webRootDir+file;
		String destDir=shopWorkDir+file;
		try {
			FileUtils.copyFile(new File(srcFile), new File(destDir), true);
		} catch (IOException e) {
			throw new BusinessException("同步文件到店铺对应目录失败！", e);
		}
	}
}
